#include "Precompile.h"
#include "DX11VertexBuffer.h"
#include "DX11RenderSystem.h"

namespace Graphics{
	DX11VertexBuffer::DX11VertexBuffer(VertexDataPtr verts, RenderContext* handle):VertexBuffer(verts,handle),m_buffer(NULL){
		DX11RenderContext* ctx = (DX11RenderContext*)handle;

		unsigned int vertWidth = unsigned int(verts->m_byteSize);
		m_stride = vertWidth;

		// Fill in a buffer description.
		D3D11_BUFFER_DESC bufferDesc;
		bufferDesc.Usage            = D3D11_USAGE_DEFAULT;
		bufferDesc.ByteWidth        = UINT(vertWidth * verts->m_numVerts);
		bufferDesc.BindFlags        = D3D11_BIND_VERTEX_BUFFER;
		bufferDesc.CPUAccessFlags   = 0;
		bufferDesc.MiscFlags        = 0;

		// Fill in the subresource data.
		D3D11_SUBRESOURCE_DATA InitData;
		InitData.pSysMem = verts->m_data;
		InitData.SysMemPitch = 0;
		InitData.SysMemSlicePitch = 0;

		HRESULT hr = ctx->m_handle->CreateBuffer(&bufferDesc,&InitData,&m_buffer);
		if(FAILED(hr)){
			LOG_ERROR("DX11VertexBuffer - Failed in creating vertex buffer.");
			assert(0);
		}
	}

	DX11VertexBuffer::~DX11VertexBuffer(){
		if(m_buffer){
			if(m_buffer->Release() != 0){
				LOG_ERROR("Referens count fault.");
				assert(0);
			}
		}
	}

	void DX11VertexBuffer::setBuffer(void* context){
		DX11RenderContext *ctx = (DX11RenderContext*)context;

		UINT offset = 0;
		ctx->m_context->IASetVertexBuffers(0,1,&m_buffer,&m_stride,&offset);
	}
}